from flask import Flask
from apscheduler.schedulers.background import BackgroundScheduler
from dotenv import load_dotenv

from app.db import connection
from app.tasks import sync_task_alerts, get_sync_interval_minutes, clean_expired_tokens

load_dotenv()

scheduler = BackgroundScheduler()


def create_app():
    app = Flask(__name__)

    # Import and register blueprints
    from .routes import main
    app.register_blueprint(main)

    # Start the scheduler with the dynamic interval from the database
    interval_minutes = get_sync_interval_minutes(connection)
    scheduler.add_job(sync_task_alerts, 'interval', minutes=interval_minutes)
    scheduler.add_job(clean_expired_tokens, 'cron', hour=0, minute=0)

    scheduler.start()

    return app
